import axios from 'axios';
import fs from 'react-native-fs';
import {Modal} from '@ant-design/react-native';
import NaviagtorService from '~/utils/navigator';
import store from '~/store';
import {saveUserInfo} from '~/store/userinfo';

const queryString = require('query-string');

let baseURL = 'https://api.lipopo.com.cn';

if (__DEV__) {
    baseURL = 'http://192.168.2.2:57717';
}

let showAlert = true;
let toLogin = true;

const services = axios.create({
    baseURL,
    timeout: 10000,
});

services.interceptors.request.use(
    (config) => {
        const getters = store.getState();
        config.params = {
            token: getters.userinfo.token,
            code: getters.userinfo.code,
        };
        return config;
    },
    (error) => {
        if (showAlert) {
            showAlert = false;
            Modal.alert('错误', error.message, [
                {
                    text: '确定',
                },
            ]);
        }
        return new Promise(() => {});
    },
);

services.interceptors.response.use(
    (response) => {
        const rsp = response.data;
        if (rsp.code === undefined) {
            return response;
        }
        if (rsp.code === 10001 || rsp.code === 10000) {
            if (toLogin) {
                toLogin = false;
                const userinfo = {
                    userid: 0,
                    owner: 0,
                    ownername: '',
                    company: 0,
                    companyname: '',
                    bank: 0,
                    bankname: '',
                    agent: 0,
                    agentname: '',
                    staff: 0,
                    staffname: '',
                    mobile: '',
                    identityname: '',
                    logo: '',
                    nickname: '',
                    token: '',
                    code: '',
                };
                store.dispatch(saveUserInfo(userinfo));
                Modal.alert('提示', rsp.msg, [
                    {
                        text: '确定',
                        onPress: () => {
                            NaviagtorService.navigate('Login');
                        },
                    },
                ]);
            }
            return new Promise(() => {});
        }
        if (rsp.code === 0) {
            toLogin = true;
            showAlert = true;
        }
        return rsp;
    },
    (error) => {
        if (showAlert) {
            showAlert = false;
            if (error.message === 'Network Error') {
                Modal.alert('错误', '无法访问服务器，请检查网络是否正常', [
                    {
                        text: '确定',
                    },
                ]);
            } else {
                Modal.alert('错误', error.message, [
                    {
                        text: '确定',
                    },
                ]);
            }
        }
        error.msg = error.message;
        return Promise.resolve(error);
    },
);

export default services;

export const upload = async (url, files, params, method) => {
    const getters = store.getState();

    const requestUrl = queryString.parseUrl(baseURL + url);
    const config = {
        token: getters.userinfo.token,
        code: getters.userinfo.code,
    };
    requestUrl.query = {...requestUrl.query, ...config};
    const toUrl = queryString.stringifyUrl(requestUrl);

    const fields = params || {};
    for (const key in fields) {
        if (typeof fields[key] === 'number') {
            fields[key] = fields[key].toString();
        }
    }

    const timeout = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve({code: 500});
        }, 15000);
    });

    const result = fs.uploadFiles({toUrl, files, fields, method}).promise.then((response) => {
        if (response.statusCode === 200) {
            return JSON.parse(response.body);
        } else {
            return Promise.resolve(response);
        }
    });

    return await Promise.race([timeout, result]);
};

export const getImageFile = (fileObj, name) => {
    const filepath = fileObj.uri.replace('file://', '');
    const lastDir = filepath.lastIndexOf('/');
    const filename = filepath.substring(lastDir + 1);
    const lastDot = filepath.lastIndexOf('.');
    let filetype = filepath.substring(lastDot + 1);
    if (filetype === 'jpg') {
        filetype = 'image/jpeg';
    } else {
        filetype = 'image/' + filetype;
    }
    return {
        name: name || 'file',
        filename,
        filepath,
        filetype,
    };
};
